"""
系统设置页面渲染模块。
"""
import streamlit as st
import datetime

# 从 app_setup 导入 logger (如果需要)
try:
    from .app_setup import logger
except ImportError:
    import logging
    logging.basicConfig(level=logging.INFO)
    logger = logging.getLogger(__name__)

def render_settings():
    """渲染系统设置界面"""
    st.markdown('<div class="main-header">系统设置</div>', unsafe_allow_html=True)

    # 创建设置表单
    # 使用 session_state 来持久化设置值是一个好主意，但这里为了简化，我们直接读取和写入
    # 在实际应用中，这些设置应该保存到配置文件或数据库中

    with st.form("settings_form"):
        st.markdown('<div class="sub-header">基本设置 (LLM)</div>', unsafe_allow_html=True)
        col1, col2 = st.columns(2)
        with col1:
            # 建议从环境变量或配置文件读取默认值
            api_key_default = st.session_state.get("settings_api_key", "sk-...")
            api_key = st.text_input("OpenAI API Key", value=api_key_default, type="password")
            model_default_index = ["gpt-4-turbo", "gpt-4-vision", "gpt-3.5-turbo"].index(st.session_state.get("settings_model", "gpt-4-turbo"))
            model = st.selectbox("OpenAI 模型", ["gpt-4-turbo", "gpt-4-vision", "gpt-3.5-turbo"], index=model_default_index)
        with col2:
            proxy_default = st.session_state.get("settings_proxy", "https://api.openai.com/v1")
            proxy = st.text_input("API代理地址", value=proxy_default, help="如需使用代理，请填写完整URL")
            temperature_default = st.session_state.get("settings_temperature", 0.2)
            temperature = st.slider("Temperature", min_value=0.0, max_value=1.0, value=temperature_default, step=0.1, help="控制生成内容的随机性")

        st.markdown('<div class="sub-header">数据源设置</div>', unsafe_allow_html=True)
        col1, col2 = st.columns(2)
        with col1:
            data_source_options = ["AKShare", "Tushare Pro", "东方财富", "聚宽JQData"]
            data_source_default_index = data_source_options.index(st.session_state.get("settings_data_source", "AKShare"))
            data_source = st.selectbox("主数据源", data_source_options, index=data_source_default_index)

            refresh_options = ["5分钟", "15分钟", "30分钟", "1小时", "仅手动刷新"]
            refresh_default_index = refresh_options.index(st.session_state.get("settings_refresh_interval", "15分钟"))
            refresh_interval = st.select_slider("数据刷新间隔", options=refresh_options, value=refresh_options[refresh_default_index])
        with col2:
            # 初始化条件变量
            tushare_token = None
            jqdata_account = None
            jqdata_password = None
            # 根据选择的数据源显示特定输入框
            if data_source == "Tushare Pro":
                tushare_token_default = st.session_state.get("settings_tushare_token", "")
                tushare_token = st.text_input("Tushare Token", value=tushare_token_default, type="password")
            elif data_source == "聚宽JQData":
                jqdata_account_default = st.session_state.get("settings_jqdata_account", "")
                jqdata_password_default = st.session_state.get("settings_jqdata_password", "")
                jqdata_account = st.text_input("聚宽账号", value=jqdata_account_default)
                jqdata_password = st.text_input("聚宽密码", value=jqdata_password_default, type="password")

        st.markdown('<div class="sub-header">多智能体设置</div>', unsafe_allow_html=True)
        col1, col2 = st.columns(2)
        with col1:
            team_size_default = st.session_state.get("settings_team_size", 5)
            team_size = st.slider("团队规模", min_value=3, max_value=8, value=team_size_default, step=1, help="智能体团队成员数量")
            team_verbose_default = st.session_state.get("settings_team_verbose", True)
            team_verbose = st.checkbox("详细日志", value=team_verbose_default, help="显示智能体决策过程的详细日志")
        with col2:
            reasoning_options = ["基础", "标准", "深度"]
            reasoning_default_index = reasoning_options.index(st.session_state.get("settings_reasoning_depth", "标准"))
            reasoning_depth = st.select_slider("推理深度", options=reasoning_options, value=reasoning_options[reasoning_default_index], help="控制智能体推理深度")
            human_feedback_default = st.session_state.get("settings_human_feedback", True)
            human_feedback = st.checkbox("人工反馈", value=human_feedback_default, help="在关键决策点允许人工干预和反馈")

        st.markdown('<div class="sub-header">回测设置</div>', unsafe_allow_html=True)
        col1, col2 = st.columns(2)
        with col1:
            backtest_start_default = st.session_state.get("settings_backtest_start", datetime.date(2024, 1, 1))
            backtest_start = st.date_input("回测起始日期", value=backtest_start_default)
            benchmark_options = ["沪深300", "上证指数", "中证500", "创业板指", "上证50"]
            benchmark_default_index = benchmark_options.index(st.session_state.get("settings_benchmark", "沪深300"))
            benchmark = st.selectbox("业绩基准", benchmark_options, index=benchmark_default_index)
        with col2:
            backtest_end_default = st.session_state.get("settings_backtest_end", datetime.date(2024, 12, 31))
            backtest_end = st.date_input("回测结束日期", value=backtest_end_default)
            commission_default = st.session_state.get("settings_commission_rate", 0.0003)
            commission_rate = st.number_input("交易佣金率", min_value=0.0, max_value=0.005, value=commission_default, format="%.5f")

        st.markdown('<div class="sub-header">提醒设置</div>', unsafe_allow_html=True)
        notification_options = ["交易信号", "重大市场波动", "持仓股票异常波动", "智能体投资建议", "系统错误警告"]
        notifications_default = st.session_state.get("settings_notifications", ["交易信号", "重大市场波动", "持仓股票异常波动"])
        notifications = st.multiselect("接收提醒", options=notification_options, default=notifications_default)

        notification_method_options = ["站内信息", "邮件通知", "两者都有"]
        notification_method_default_index = notification_method_options.index(st.session_state.get("settings_notification_method", "站内信息"))
        notification_method = st.radio("提醒方式", notification_method_options, index=notification_method_default_index)

        # 提交按钮
        submitted = st.form_submit_button("保存设置")

        if submitted:
            # 保存设置到 session_state (或配置文件/数据库)
            st.session_state.settings_api_key = api_key
            st.session_state.settings_model = model
            st.session_state.settings_proxy = proxy
            st.session_state.settings_temperature = temperature
            st.session_state.settings_data_source = data_source
            st.session_state.settings_refresh_interval = refresh_interval
            # 根据 data_source 保存特定设置
            if data_source == "Tushare Pro":
                # 检查 tushare_token 是否已定义 (虽然在此流程中它应该已定义)
                if 'tushare_token' in locals():
                    st.session_state.settings_tushare_token = tushare_token
                else:
                    # 如果未定义（理论上不应发生），可以记录警告或设置默认值
                    logger.warning("尝试保存 tushare_token 时未找到该变量。")
                    st.session_state.settings_tushare_token = "" # 或 None
            elif data_source == "聚宽JQData":
                # 检查 jqdata_account 和 jqdata_password 是否已定义
                if 'jqdata_account' in locals() and 'jqdata_password' in locals():
                    st.session_state.settings_jqdata_account = jqdata_account
                    st.session_state.settings_jqdata_password = jqdata_password # 注意：密码处理需谨慎
                else:
                    logger.warning("尝试保存聚宽凭证时未找到相应变量。")
                    st.session_state.settings_jqdata_account = "" # 或 None
                    st.session_state.settings_jqdata_password = "" # 或 None
            st.session_state.settings_team_size = team_size
            st.session_state.settings_team_verbose = team_verbose
            st.session_state.settings_reasoning_depth = reasoning_depth
            st.session_state.settings_human_feedback = human_feedback
            st.session_state.settings_backtest_start = backtest_start
            st.session_state.settings_backtest_end = backtest_end
            st.session_state.settings_benchmark = benchmark
            st.session_state.settings_commission_rate = commission_rate
            st.session_state.settings_notifications = notifications
            st.session_state.settings_notification_method = notification_method

            logger.info("系统设置已保存到 session_state。")
            st.success("设置已保存！")
            # 可以在这里添加调用函数来实际应用这些设置，例如重新初始化 LLM 或数据连接器